var layer = layui.layer //弹层
    , table = layui.table //表格
    , form = layui.form,
    $ = layui.jquery;

//联系人
function getAllJsonIC(jsons) {
    let tmpitem = []
    for (let item of jsons) {
        let tmparr = {}
        if (item["email"]){
            tmparr["value"] = item["email"]
        }else {
            tmparr["value"] = Number(Math.random().toString().substr(3,3) + Date.now()).toString(36);
        }

        tmparr["name"] = item["name"] + "<" + item["email"] + ">";
        if (item["users"]) {
            for (let it of item["users"]) {
                item["list"].push(it)
            }
        }
        if (item["list"] && item["list"].length) {
            tmparr["children"] = this.getAllJsonIC(item["list"]);
            tmpitem.push(tmparr)
        } else {
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
function getxmselectIC(el, name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        autoRow: false,
        filterable: true,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon: true,
            indent: 20,
            expandedKeys: false
        },
        height: 'auto',
        data: data
    })
}

//业务员
function getxmselectS(el, name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        autoRow: false,
        filterable: true,
        initValue:[user.code],
        tree: {
            show: true,
            showLine: true,
            showFolderIcon: true,
            indent: 20,
            expandedKeys: false
        },
        height: 'auto',
        data: data
    })
}

function getAllJsonS(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJsonS(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
//显示类型
function getxmlselectCT(fls){
    tmparr=[]
    for(let item of fls){
        tmparr.push({value:item.code,name:item.name})
    }
    return tmparr
}
function getxmselectCT(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
    })
}
//获取所有用户所管理的部门
function getAllDepartmentUser() {
    let userTree = {};
    $.ajax({
        type: 'get',
        url: 'department/getCurrentDepartmentUser',
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.status == 200) {
                userTree = data.data;
            }
        },
        error: function (data) {
        }
    });
    return userTree;

}
//内部联系人
let internalContactList=[];
layer.ready(function () {

    //联系人，获取当前用户的部门及人员结构树
    let userList = getAllDepartmentUser();
    if (userList && userList.list) {
        let userTree = getAllJsonIC(userList.list);
        internalContactList=getxmselectIC("#customerRole", "customerRole", userTree)
    } else {
        internalContactList=getxmselectIC("#customerRole", "customerRole", [{name: user.name, value: user.code}])
    }

    //业务员
    let treeList = getCurrentDepartmentUser();
    if(treeList && treeList.list){
        let userTree = getAllJsonS(treeList.list);
        getxmselectS("#skssywy","skssywy", userTree)
    }else {
        getxmselectS("#skssywy","skssywy", [{name: user.name, value: user.code}])
    }
    //客户类型
    let customerTypeList=getdictionary(6,27);//客户类型
    getxmselectCT("#sklx","sklx", getxmlselectCT(customerTypeList));

});

//选中客户编码,以逗号隔开
let customerCodeStr="";
//选中客户联系人数据
let customerContactStr="";//存储取消选择联系人
// 客户信息
table.render({
    elem: '#table-customer'
    , data:[]
    , id: "customer"
    , url:"basicInformation/getCustomerByPage"
    , cols: [[
        {type: 'checkbox',fixed: 'left'}
        , {field: 'typeName', title: '客户类型', fixed: true}
        , {field: 'name', title: '客户名称', fixed: true, event: "customerstname"}
        , {field: 'code', title: '客户代码', fixed: true, event: "cucustomerscode"}
        , {field: 'abbreviation', title: '简称', fixed: true, event: "referred"}
        , {field: 'country', title: '国家', fixed: true}
    ]]
    , page: true
    , loading: true
    , size: "sm"
    , done(res) {
        if (res.data.length>0){
            table.render({
                elem: "#table-contacts"
                , id: "contacts"
                , data:[]
                , where:{
                    "userCode":res.data[0].code //默认第一条信息，数据为空则客户编码code为空
                }
                , title: '联系人信息'
                , url:"basicInformation/getCustomerContactList"
                , cols: [[
                    {type: 'checkbox', fixed: 'left'}
                    , {field: 'name', title: '用户名', width: 300, edit: 'text'}
                    , {
                        field: 'email', title: '邮箱', width: 300, templet: function (res) {
                            return '<em>' + res.email + '</em>'
                        }
                    }
                    , {field: 'post', title: '职务', width: 300, sort: true}

                ]]
                , size: "sm"
                , done(e) {

                }
            })
        }

    }
});

//搜索
form.on("submit(filcustormer)", function (e) {
    let req={
        "name":e.field.skmc,
        "type":e.field.sklx,
        "salesman":e.field.skssywy,
        "code":e.field.kfbm,
        "abbreviation":e.field.kfjc
    }
    if(req.salesman==""||req.salesman==null){
        req.salesman=user.code;
    }
    table.reload('customer', {
        page: {
            limit:10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: req
    }, 'data');
    return false;
});
//一级复选框监听
table.on("checkbox(customerEvent)", async function (obj) {
    //开始为空数组 之后的点击使用上次的数据
    let customerCodeArray=[];
    if (customerCodeStr!=""){
        customerCodeArray=customerCodeStr.split(',');
    }
    if(obj.type=="all"){//全选
        var checkStatus = table.checkStatus('customer').data;
        if (obj.checked) {//全选
            for(let i in checkStatus){
                customerCodeArray.push(checkStatus[i].code);
            }
        } else {//取消全选
            customerCodeArray=[];
        }
    }else {
        if (obj.checked) {//单点，选中
            if(customerCodeStr.indexOf(obj.data.code)===-1){
                customerCodeArray.push(obj.data.code);
            }
        } else {//单点，取消选中
            if(customerCodeStr.indexOf(obj.data.code)!=-1){
                customerCodeArray=customerCodeArray.filter((code)=>{
                    return code!=obj.data.code;
                })
            }
        }
    }

    //数组转换
    customerCodeStr=customerCodeArray.join(',');
    if (customerCodeStr!=""){
        //二级表格重载
        table.reload('contacts', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            ,where: {"userCode":customerCodeStr}
        }, 'data');
    }


})

//二级复选框监听
table.on("checkbox(contactsEvent)", function (obj) {
    let customerContactArray=[];
    if (customerContactStr!=""){
        customerContactArray=customerContactStr.split(',');
    }
    if(obj.type=="all"){//全选
        var checkStatus = table.checkStatus('contacts').data;
        if (obj.checked) {//全选
            for(let i in checkStatus){
                customerContactArray.push(checkStatus[i].email);
            }
        } else {//取消全选
            customerContactArray=[];
        }
    }else {
        if (obj.checked) {//选中
            if(customerContactStr.indexOf(obj.data.email)===-1){
                customerContactArray.push(obj.data.email);
            }
        }else {//取消选中
            if(customerContactStr.indexOf(obj.data.code)!=-1){
                customerContactArray=customerContactArray.filter((email)=>{
                    return email!=obj.data.email;
                })
            }
        }
    }
    //数组转换
    customerContactStr=customerContactArray.join(',');
})


//回调函数
var callbackdata = function () {
    let address=customerContactStr;
    let internalContactStr=internalContactList.getValue('valueStr')
    if (internalContactStr!=""||internalContactStr!=null){
        if (address!=""){
            address=address+','+internalContactStr;
        }else {
            address=internalContactStr;
        }

    }
    var data = {
        "address":address
    };
    return data;
}


























































/*
var layer = layui.layer //弹层
    , table = layui.table //表格
    , form = layui.form, $ = layui.jquery, laydate = layui.laydate,tagsInput=layui.tagsInput;


lay('.starttime').each(function () {
    laydate.render({
        elem: this
    });
});

function getAllJson(jsons) {
    let tmpitem = []
    for (let item of jsons) {
        let tmparr = {}
        tmparr["value"] = item["email"]
        tmparr["name"] = item["name"] + "<" + item["email"] + ">";
        if (item["users"]) {
            for (let it of item["users"]) {
                item["list"].push(it)
            }
        }
        if (item["list"] && item["list"].length) {
            tmparr["children"] = this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        } else {
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el, name, data) {
    return demo1=xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon: true,
            indent: 20,
            expandedKeys: false,
            clickExpand: true,

        },
        autoRow: true,
        height: 'auto',
        data: data,
        id:'demoId',
        on: function ({arr, change, isAdd}) {
            return this
        }
    })
}

//获取所有用户所管理的部门
function getAllDepartmentUser() {
    let userTree = {};
    $.ajax({
        type: 'get',
        url: 'department/getCurrentDepartmentUser',
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.status == 200) {
                userTree = data.data;
            }
        },
        error: function (data) {
        }
    });
    return userTree;

}

//select over

//获取当前用户的部门及人员结构树
let userList = getAllDepartmentUser();
if (userList && userList.list) {
    let userTree = getAllJson(userList.list);
    getxmselect("#customerRole", "customerRole", userTree)
} else {
    getxmselect("#customerRole", "customerRole", [{name: user.name, value: user.code}])
}


form.on('submit(submitform)', function (data) {
    let operationCode = data.field.operationCode;

});


form.on('radio(ccpeopleradio1)', function (data) {
    var level = data.value;//被点击的radio的value值
    //切换数据源
});

// start

let customers=new Map();//存储选择客户
let customerContactList=new Map();//存储取消选择联系人
// 表单搜索监听
form.on("submit(filcustormer)", function (e) {
    let s={
        "name":e.field.skmc,
        "type":e.field.sklx,
        "salesman":e.field.skssywy,
        "code":e.field.kfbm,
        "abbreviation":e.field.kfjc
    }
    if(s.salesman==""||s.salesman==null){
        s.salesman=user.code;
    }
    setcustomer(s)
})
form.on("submit(filcontacts)", function (e) {
     let company=""
    customers.forEach(function (value, key, map) {
        company+=value.code+","
    })
    setcontacts({"userCode":company})
})


// 客户信息
function setcustomer(data) {
    table.render({
        elem: '#table-customer'
        , id: "customer"
        ,url:"basicInformation/getCustomerByPage"
        ,where:data
        , cols: [[
            {type: 'checkbox',fixed: 'left'}
            // , { field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true }
            , {field: 'typeName', title: '客户类型', fixed: true}
            , {field: 'name', title: '客户名称', fixed: true, event: "customerstname"}
            , {field: 'code', title: '客户代码', fixed: true, event: "cucustomerscode"}
            , {field: 'abbreviation', title: '简称', fixed: true, event: "referred"}
            , {field: 'country', title: '国家', fixed: true}
            // , {field: 'level', title: '客户等级', fixed: true}
            // , {field: 'sourceOfCustomers', title: '客户来源', fixed: true}
            // , {field: 'businessType', title: '业务类型', fixed: true}
        ]]
        , page: true
        , loading: true
        , size: "sm"
        , done(e) {
            table.on("checkbox(customerEvent)", async function (obj) {
                if(obj.type=="all"){//全选
                    var checkStatus = table.checkStatus('customer').data;
                    if (obj.checked) {//全选
                           for(let i in checkStatus){
                               customers.set(checkStatus[i].id,checkStatus[i])
                           }
                        } else {
                        for(let i in checkStatus){
                            if(customers.has(checkStatus[i].id)){
                                customers.delete(checkStatus[i].id)
                            }
                        }
                    }
                }else {
                    if (obj.checked) {
                        customers.set(obj.data.id,obj.data)
                    } else {
                       if(customers.has(obj.data.id)){
                           customers.delete(obj.data.id)
                       }
                    }
                }
            })
        }
    });

}

// 联系人信息
function setcontacts(data = []) {
    // table-contacts
    table.render({
        elem: "#table-contacts"
        , id: "contacts"
        , title: '联系人信息'
        ,url:"basicInformation/getCustomerContactList"
        ,where:data
        , cols: [[
            {type: 'checkbox', LAY_CHECKED:true, fixed: 'left'}
            , {field: 'name', title: '用户名', width: 300, edit: 'text'}
            , {
                field: 'email', title: '邮箱', width: 300, templet: function (res) {
                    return '<em>' + res.email + '</em>'
                }
            }
            , {field: 'post', title: '职务', width: 300, sort: true}

        ]]
        , size: "sm"
        , done(e) {
            table.on("checkbox(contactsEvent)", function (obj) {
                if(obj.type=="all"){//全选
                    var checkStatus = table.checkStatus('contacts').data;
                    if (obj.checked) {//全不选
                        for(let i in checkStatus){
                            customerContactList.set(checkStatus[i].id,checkStatus[i])
                        }
                    } else {
                        for(let i in checkStatus){
                            if(customerContactList.has(checkStatus[i].id)){
                                customerContactList.delete(checkStatus[i].id)
                            }
                        }
                    }
                }else {
                    if (obj.checked) {//选中
                        customerContactList.set(obj.data.id,obj.data)
                    }else {
                        if(customerContactList.has(obj.data.id)){
                            customerContactList.delete(obj.data.id)
                        }
                    }
                }
            })

        }
    })
}

//回调函数
var callbackdata = function () {
    //提交第一步，获取到联系人的所有email地址
    debugger
    var s1=demo1.getValue();
    var email=''
    if(s1.length>0){
        for(let i in s1){
            email+=s1[i].value+","
        }
    }
    var reg = new RegExp(";" , 'g');//g就是代表全部
    email=email.replace(reg , "," || '');
    //第二步，获取到客户联系人数据
    let company=""
    customers.forEach(function (value, key, map) {
        company+=value.code+","
    })
    var address=""
    let custArray=new Array();
    customerContactList.forEach(function (value, key, map) {
        custArray.push(value)
    })
    $.ajax({
        url: 'email/getCustomerscontact?company='+company+'&email='+email,
        type: 'POST',
        contentType: "application/json;charset=utf-8",
        async: false, // 同步
        data: JSON.stringify(custArray),
        success: function (data) {
            address=data.data
        }
    })
    var data = {
        "address":address
    };
    return data;
}

//业务员
function getxmselectS(el, name, data) {
    xmSelect.render({
        el: el,
        name: name,
        autoRow: false,
        filterable: true,
        initValue:[user.code],
        tree: {
            show: true,
            showLine: true,
            showFolderIcon: true,
            indent: 20,
            expandedKeys: false
        },
        height: 'auto',
        data: data
    })
}

function getAllJsonS(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJsonS(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
let treeList2 = getCurrentDepartmentUser();
if(treeList2 && treeList2.list){
    let userTree2 = getAllJsonS(treeList2.list);
    getxmselectS("#skssywy","skssywy", userTree2)
}else {
    getxmselectS("#skssywy","skssywy", [{name: user.name, value: user.code}])
}
//显示类型
function getxmlselectCT(fls){
    tmparr=[]
    for(let item of fls){
        tmparr.push({value:item.code,name:item.name})
    }
    return tmparr
}
function getxmselectCT(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
    })
}
let customerTypeList=getdictionary(6,27);//客户类型
getxmselectCT("#sklx","sklx", getxmlselectCT(customerTypeList));











*/
